package com.sx.entity.system;

import com.alibaba.fastjson.annotation.JSONField;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.sx.basic.BasicEntity;
import com.sx.basic.enums.HttpMethod;
import com.sx.basic.serializer.LongToStringSerializer;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author AdinZ
 * @date 2020/11/7 10:13
 */
@Data
@TableName(value = "sx_menu")
@Entity
@Table(name = "sx_menu")
public class MenuEntity  extends BasicEntity {
    @TableId(type = IdType.AUTO)
    @Id @GeneratedValue
    private Long id;
    /**
     * 多平台时,可用,
     * 0 可系统平台,
     * 其他  可以是店铺, 代理商, 等等 ,其他管理后台的菜单
     */
    @ApiModelProperty("用户方id")
    @JSONField(serializeUsing = LongToStringSerializer.class)
    private long tid=0;
    @ApiModelProperty("菜单url")
    private String url;//菜单地址
    @ApiModelProperty("菜单名称")
    @TableField("_text")@Column(name = "_text")
    private String text; //菜单名称
    @ApiModelProperty("图标,可选")
    private String icon; //图标
    @ApiModelProperty("菜单上级id")
    @JSONField(serializeUsing = LongToStringSerializer.class)
    private long pid; //上级id
    @ApiModelProperty("菜单路由,可选")
    private String route;//路由
    @ApiModelProperty("菜单类型")
    @Enumerated(EnumType.STRING)
    private Action action;
    @ApiModelProperty("接口请求方式")
    @Enumerated(EnumType.STRING)
    private HttpMethod method;
    @ApiModelProperty("是否隐藏")
    private boolean hide = false;
    @ApiModelProperty("备注说明")
    private String remark;

    @ApiModelProperty("下级菜单")
    @TableField(exist = false)
    private @Transient List<MenuEntity> child;

    public static String KEY(Action action) {
        return "MENU___"+action;
    }


    public enum Action{
        //系统接口,
        SYSTEM_API,
        // webui 页面路径
        UI,
        //用户api
        API
    }


    public static List<MenuEntity> toChild(List<MenuEntity> list,long pid) {
        List<MenuEntity> result = new ArrayList<>();
        for (MenuEntity m : list) {
            if (m.getPid() == pid) {
                List<MenuEntity> l = toChild(list, m.getId());
                m.setChild(l);
                result.add(m);
            }
            if(m.getChild()!=null&&m.getChild().size()==0)
                m.setChild(null);
        }
        return result;
    }

}
